<template>
  <div>
    <div class="add-btn">
      <el-button type="primary" size="small" @click="showDialog"><i class="el-icon-plus"></i> 添加授权账号</el-button>
    </div>
    <div class="table-box">
      <!-- 授权列表（为空）开始 -->
      <template v-if="proUserList.length == 0">
        <p>您还没有添加用户授权账号，请点击按钮进行添加。</p>
      </template>
      <!-- 授权列表（为空）结束 -->
      <!-- 授权账号列表（不为空）开始 -->
      <template v-else>
        <ElTable refName="proUserList" @pageChange="pageChange" :data-source="proUserList" :data-config="tableConfig"
          :total="total" :pageSize="pageSize" :pageNum="pageNum" :isLoading="isLoading">
          <template #operate="{ scope }">
            <el-button type="primary" size="mini" @click="showEditDialog(scope.row)">修改</el-button>
            <el-button size="mini" @click.native="deleteProUser(scope.row)">删除</el-button>
          </template>
        </ElTable>
      </template>

      <!-- 授权账号列表（不为空）结束 -->
      <!-- 授权对话框开始 -->
      <el-dialog :title="title" :visible.sync="dialogVisible" width="600px" @close="closeDialog()">
        <el-row type="flex" justify="center">
          <el-col :xs="20" :sm="20" :md="20" :lg="22">
            <p>{{ desc }}</p>
            <el-form :model="dataForm" :rules="rulesForm" ref="empowerRef" label-width="85px" label-position="right" size="small">
              <el-form-item label="手机号" prop="mobile" v-if="dataForm.id">
                <span>{{  dataForm.mobile  }}</span>
              </el-form-item>
              <el-form-item label="手机号" prop="mobile" v-else>
                <el-input v-model="dataForm.mobile" placeholder="11位正确的手机号"></el-input>
              </el-form-item>
              <el-form-item label="姓 名" prop="name">
                <el-input v-model="dataForm.name" placeholder="姓名长度不超过20个字"></el-input>
              </el-form-item>
              <el-form-item label="开始时间" prop="startOn">
                <el-date-picker v-model="dataForm.startOn" type="date" placeholder="若为空则默认为系统时间"
                  :picker-options="forbiddenTime">
                </el-date-picker>
              </el-form-item>
              <el-form-item label="过期时间" prop="endOn">
                <el-date-picker v-model="dataForm.endOn" type="date" placeholder="若为空则授权长久有效"
                  :picker-options="forbiddenTime">
                </el-date-picker>
              </el-form-item>
              <el-form-item label="审批权限" prop="approve">
                <el-select v-model="dataForm.approve" placeholder="请选择">
                  <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="授权状态" prop="status" v-if="dataForm.id">
                <el-select v-model="dataForm.status" placeholder="请选择">
                  <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-form>
          </el-col>
        </el-row>
        <span slot="footer" class="dialog-footer">
          <el-button size="small" @click="closeDialog">取 消</el-button>
          <el-button size="small" type="primary" @click="proUserSubmit" :loading="btnLoading">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 授权对话框结束 -->

      </div>

  </div>
</template>

<script>
import {
  list,
  update,
  del
} from "@/api/member/empower";
import ElTable from "@/components/table/ElTable.vue";
import { checkPhone } from "../../utils/common";
export default {
  props: {
    title: {
      type: String,
      default: "添加授权账号",
    },
    desc: {
      type: String,
      default: "您可以在这里新增您的授权账号，初始密码为手机号后六位。",
    },
  },
  data() {
    return {
      forbiddenTime: {
        //禁用当前日期之前的日期
        disabledDate(time) {
          return time.getTime() < Date.now() - 8.64e7;
        },
      },
      proUserList: [],
      tableConfig: [
        {
          prop: "mobile",
          label: "手机号",
        },
        {
          prop: "name",
          label: "姓名",
        },
        {
          prop: "startOn",
          label: "开始时间",
        },
        {
          prop: "endOn",
          label: "过期时间",
        },
        {
          prop: "approveDesc",
          label: "审批权限"
        },
        {
          prop: "statusDesc",
          label: "授权状态"
        },
        {
          prop: "operate",
          label: "操作",
        },
      ],
      isLoading: false,
      btnLoading: false,
      total: 0,
      pageSize: 10,
      pageNum: 1,
      dataForm: {
        approve: 1
      },
      rulesForm: {
        mobile: [
          { required: true, message: "请输入手机号" },
          { validator: checkPhone, trigger: ["blur", "change"] },
        ],
        name: [{ required: true, message: "请输入姓名" }]
      },
      options: [
        {
          value: 1,
          label: "启用"
        },
        {
          value: 0,
          label: "禁用"
        }
      ],
      dialogVisible: false
    };
  },
  components: {
    ElTable
  },
  mounted() {
    this.getProUserList();
  },

  methods: {
    // 分页变化
    pageChange(emitData) {
      this.pageNum = emitData.pageNum;
      this.pageSize = emitData.pageSize;
      this.getProUserList();
    },

    // 获得授权列表
    getProUserList() {
      const params = {
        pageSize: this.pageSize,
        pageNum: this.pageNum,
      };
      this.isLoading = true;
      list(params)
        .then((res) => {
          res.data.map((e) => {
            e.statusDesc = e.status == 1 ? '启用' : '禁用';
            e.approveDesc = e.approve == 1 ? '启用' : '禁用';
            e.startOn = e.startOn == 0 ? "" : this.$moment(e.startOn * 1000).format(
              "YYYY-MM-DD"
            );
            e.endOn = e.endOn == 0 ? "" : this.$moment(e.endOn * 1000).format(
              "YYYY-MM-DD"
            );
          });
          this.proUserList = res.data;
          this.total = res.total;
          this.isLoading = false;
        })
        .catch((err) => {
          this.isLoading = false;
        });
    },   

    // 删除授权账号
    deleteProUser(row) {
      this.$confirm("此操作将删除该授权账号, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          const data =  [row.id];
          del(data).then((res) => {
            if (res.code === 200) {
              this.$message({
                type: "success",
                message: "删除成功!",
              });              
              this.getProUserList();
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },

    // 打开授权账号对话框
    showDialog() {
      this.dialogVisible = true;
    },

    // 修改授权账号对话框
    showEditDialog(row) {
      this.title = "修改授权账号";
      this.desc = "授权状态的“启用”表示已授权，“禁用”表示取消授权。审批权限的“启用”表示授权账号有审批权限，“禁用”表示无审批权限。";
      this.dataForm = row;
      this.dialogVisible = true;
    },

    // 提交授权账号
    proUserSubmit() {
      this.$refs.empowerRef.validate(valid => {
        if (valid) {
          this.btnLoading = true;
          const data = {
            ...this.dataForm,
            startOn: parseInt(new Date(this.dataForm.startOn).getTime() / 1000),
            endOn: parseInt(new Date(this.dataForm.endOn).getTime() / 1000)
          };
          update(data).then((res) => {
            this.$message({
              message: res.msg,
              type: "success",
            });
            this.btnLoading = false;
            this.dialogVisible = false;
            this.getProUserList();
          }).catch((err) => {
            this.btnLoading = false;
          });
        }
      });
    },

    // 关闭授权账号对话框
    closeDialog() {
      this.dataForm = {
        approve: 1
      };
      this.dialogVisible = false;
      // 重置表单
      this.$refs.empowerRef.resetFields();
      this.getProUserList();
    },

  }
};
</script>

<style scoped>
p {
  margin: 15px auto;
  line-height: 20px;
}

.add-btn {
  margin-bottom: 10px;
}
</style>

